package etcdUtils

import (
	"context"
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"log"
)

// EtcdDiscovery 实现 Etcd 服务发现功能
type EtcdDiscovery struct {
	Client *clientv3.Client // Etcd 客户端
}

// Discover 获取指定服务名的服务地址列表
func (d *EtcdDiscovery) Discover(ctx context.Context, serviceName string) ([]string, error) {
	// 获取服务前缀
	prefix := fmt.Sprintf("/%s/", serviceName)

	// 获取服务列表
	resp, err := d.Client.Get(ctx, prefix, clientv3.WithPrefix())
	if err != nil {
		return nil, err
	}

	// 解析服务地址列表
	addrs := make([]string, 0, len(resp.Kvs))
	for _, kv := range resp.Kvs {
		addrs = append(addrs, string(kv.Value))
	}

	return addrs, nil
}
func NewDis(endpoints ...string) (register *EtcdDiscovery) {
	client, err := clientv3.New(clientv3.Config{
		Endpoints: endpoints, // Etcd 服务器地址
	})
	if err != nil {
		log.Fatal(err)
	}

	// 创建服务注册器
	register = &EtcdDiscovery{
		Client: client,
	}
	return

}
